import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import type { User, LoginRequest, LoginResponse, Role } from '@/types/auth'

/**
 * 认证状态管理
 */
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(null)
  const permissions = ref<string[]>([])

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  /**
   * 设置认证信息
   * @param authData 认证数据
   */
  const setAuth = (authData: LoginResponse) => {
    token.value = authData.access_token
    user.value = authData.user
    permissions.value = authData.permissions || []
    
    // 保存到本地存储
    localStorage.setItem('token', authData.access_token)
    localStorage.setItem('user', JSON.stringify(authData.user))
    localStorage.setItem('permissions', JSON.stringify(authData.permissions || []))
    
    // 设置axios默认请求头
    axios.defaults.headers.common['Authorization'] = `Bearer ${authData.access_token}`
  }

  /**
   * 清除认证信息
   */
  const clearAuth = () => {
    token.value = null
    user.value = null
    permissions.value = []
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('permissions')
    
    // 清除axios默认请求头
    delete axios.defaults.headers.common['Authorization']
  }

  /**
   * 登录
   * @param credentials 登录凭据
   */
  const login = async (credentials: LoginRequest): Promise<void> => {
    try {
      const response = await axios.post<LoginResponse>('/api/auth/login', credentials)
      setAuth(response.data)
    } catch (error) {
      clearAuth()
      throw error
    }
  }

  /**
   * 登出
   */
  const logout = async (): Promise<void> => {
    try {
      if (token.value) {
        await axios.post('/api/auth/logout')
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      clearAuth()
    }
  }

  /**
   * 刷新用户信息
   */
  const refreshUser = async (): Promise<void> => {
    if (!token.value) return

    try {
      const response = await axios.get<User>('/api/auth/profile')
      user.value = response.data
      localStorage.setItem('user', JSON.stringify(response.data))
    } catch (error) {
      console.error('Refresh user error:', error)
      clearAuth()
      throw error
    }
  }

  /**
   * 检查是否有指定权限
   * @param permission 权限标识
   */
  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission)
  }

  /**
   * 检查是否有指定角色
   * @param role 角色名称
   */
  const hasRole = (role: string): boolean => {
    return user.value?.roles?.some((r: Role) => r.name === role) || false
  }

  /**
   * 初始化认证状态
   */
  const initAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    const savedPermissions = localStorage.getItem('permissions')

    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
      permissions.value = savedPermissions ? JSON.parse(savedPermissions) : []
      
      // 设置axios默认请求头
      axios.defaults.headers.common['Authorization'] = `Bearer ${savedToken}`
    }
  }

  return {
    // 状态
    token,
    user,
    permissions,
    
    // 计算属性
    isAuthenticated,
    
    // 方法
    setAuth,
    clearAuth,
    login,
    logout,
    refreshUser,
    hasPermission,
    hasRole,
    initAuth
  }
})